package com.cn.aam.checaiduo.backend;


import com.cn.aam.checaiduo.backend.api.InternalApi;
import com.cn.aam.checaiduo.backend.api.UserApi;
import com.cn.aam.checaiduo.backend.utils.OKHttpsUtils;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.cn.aam.checaiduo.BuildConfig.HOST;


public class RetrofitHome {

    public static String HOST_API = HOST;
    private Retrofit retrofit;
    private boolean isChangeBaseUrl = false;//是否修改了BaseUrl

    //service
    private static UserApi userApi;
    private static InternalApi internalApi;

    //获取单例
    public static RetrofitHome getInstance() {
        return SingletonHolder.INSTANCE;
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder {
        private static final RetrofitHome INSTANCE = new RetrofitHome();
    }

    //构造方法私有
    private RetrofitHome() {
        retrofit = new Retrofit.Builder()
                .client(OKHttpsUtils.getSessionOKHttpClient())
                .addConverterFactory(GsonConverterFactory.create())//Gson进行转化
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//RxJava进行一处处理
                .baseUrl(HOST_API)
                .build();
    }


    public UserApi getUserApi() {
        checkBaseUrl();
        return userApi == null ? retrofit.create(UserApi.class) : userApi;
    }

    public InternalApi getInternalApi() {
        checkBaseUrl();
        return internalApi == null ? retrofit.create(InternalApi.class) : internalApi;
    }

    //检查是否修改BaseUrl是否有修改
    private void checkBaseUrl() {
        if (isChangeBaseUrl) {
            isChangeBaseUrl = false;
        } else {
            retrofit = retrofit.newBuilder().baseUrl(HOST_API).build();
        }
    }

    //修改BaseURl
    public RetrofitHome modifyBaseUrl(String baseUrl) {
        retrofit = retrofit.newBuilder().baseUrl(baseUrl).build();
        isChangeBaseUrl = true;
        return this;
    }


    public Retrofit getRetrofit() {
        return retrofit;
    }


}
